import 'package:flutter/material.dart';
import 'package:wuliu01/utils/http.dart';
import 'package:wuliu01/utils/token.dart';

class Waittinggoods extends StatefulWidget {
  const Waittinggoods({super.key});

  @override
  State<Waittinggoods> createState() => _WaittinggoodsState();
}

class _WaittinggoodsState extends State<Waittinggoods> {
  //上拉加载
  ScrollController _scrollController = ScrollController();
  bool _isLoading = false;

  //下拉刷新
  Future<void> _refreshData() async {
    try {
      var res = await http.get(
        '/driver/tasks/list',
        params: {'page': 1, 'pageSize': 10, 'status': 1},
      );
      setState(() {
        dataList = res['data']['items']; // 直接替换为最新数据
      });
    } catch (e) {
      debugPrint('刷新失败：$e');
    }
  }

  //拿到实例
  final tokenManager = TokenManager();

  //数据数组
  List dataList = [
    //任务编号 id
    //寄件地址 startAddress
    //收件地址 endAddress
    //提货时间 planDepartureTime

    /*
      'id': '',
      'startAddress': "辽宁抚顺顺城鸭绿江北街58-8号",
      'endAddress': "湖北武汉武昌友谊大道194号附近",
      'planDepartureTime': "2025-05-24 20:00:00",
      */
  ];

  //打开页面就执行
  void getData() async {
    try {
      //拿到存储的token
      //var tokendata = TokenManager().getToken();
      var res = await http.get(
        '/driver/tasks/list',
        params: {'page': 1, 'pageSize': 10, 'status': 1},
      );
      //拿到data里的数据
      var first = res['data'];
      setState(() {
        //拿到data里的items=房屋列表
        dataList = first['items'];
      });
      debugPrint('请求成功：$dataList');
    } catch (e) {
      debugPrint('请求失败：$e');
    }
  }

  //生命周期函数
  @override
  void initState() {
    super.initState();
    getData();
    //
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
              _scrollController.position.maxScrollExtent &&
          !_isLoading) {
        _loadMore();
      }
    });
  }

  Future<void> _loadMore() async {
    setState(() => _isLoading = true);
    try {
      var res = await http.get(
        '/driver/tasks/list',
        params: {
          'page': (dataList.length ~/ 10) + 1,
          'pageSize': 10,
          'status': 1,
        }, // 分页逻辑
      );
      setState(() {
        dataList.addAll(res['data']['items']); // 合并新数据
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      debugPrint('加载更多失败：$e');
    }
  }

  //释放
  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _refreshData,
        child: Container(
          decoration: BoxDecoration(),
          child: ListView.builder(
            controller: _scrollController,
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              if (index == dataList.length) {
                return _isLoading
                    ? Center(child: CircularProgressIndicator())
                    : Container();
              }
              return GestureDetector(
                onTap: () {},
                child: Container(
                  margin: EdgeInsets.only(
                    top: 15,
                    bottom: 15,
                    right: 15,
                    left: 15,
                  ),
                  padding: EdgeInsets.only(
                    top: 15,
                    bottom: 24,
                    right: 20,
                    left: 20,
                  ),
                  width: 375,
                  height: 260,
                  color: const Color.fromARGB(255, 255, 255, 255),
                  alignment: Alignment.centerLeft,
                  child: Column(
                    children: [
                      //任务编号
                      Row(
                        children: [
                          Text(
                            '任务编号 : ${dataList[index]['id']}',
                            style: TextStyle(fontWeight: FontWeight.w600),
                          ),
                          const SizedBox(width: 80),
                          Text('已延迟', style: TextStyle(color: Colors.red)),
                        ],
                      ),
                      const SizedBox(height: 20),

                      Column(
                        children: [
                          //起
                          Row(
                            children: [
                              Container(
                                width: 22, // 容器宽度
                                height: 22, // 容器高度
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: const Color.fromARGB(
                                    255,
                                    0,
                                    0,
                                    0,
                                  ), // 关键属性
                                ),
                                alignment: Alignment.center,

                                child: Text(
                                  '起',
                                  style: TextStyle(
                                    color: Colors.white, // 白色文字
                                    fontSize: 12, // 字号大小
                                    fontFamily: 'Heiti', // 黑体风格（需确保设备支持）
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 15),
                              Text(
                                '${dataList[index]['startAddress']}',
                                style: TextStyle(color: Colors.grey),
                              ),
                            ],
                          ),
                          const SizedBox(height: 25),

                          //止
                          Row(
                            children: [
                              Container(
                                width: 22, // 容器宽度
                                height: 22, // 容器高度
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: const Color.fromARGB(
                                    255,
                                    255,
                                    26,
                                    26,
                                  ), // 关键属性
                                ),
                                alignment: Alignment.center,

                                child: Text(
                                  '止',
                                  style: TextStyle(
                                    color: Colors.white, // 白色文字
                                    fontSize: 12, // 字号大小
                                    fontFamily: 'Heiti', // 黑体风格（需确保设备支持）
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 15),
                              Text(
                                '${dataList[index]['endAddress']}',
                                style: TextStyle(color: Colors.grey),
                              ),
                            ],
                          ),
                          const SizedBox(height: 15),
                        ],
                      ),
                      const SizedBox(height: 15),

                      //横线
                      Divider(
                        height: 20, // 控制分割线上下间距（非线条粗细）
                        thickness: 2, // 线条实际粗细
                        color: const Color.fromARGB(255, 228, 228, 228),
                        indent: 3, // 左侧缩进
                        endIndent: 3, // 右侧缩进
                      ),

                      //提货时间和提货
                      const SizedBox(height: 15),
                      Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '提货时间',
                                style: TextStyle(color: Colors.grey),
                              ),
                              const SizedBox(height: 5),
                              Text('${dataList[index]['planDepartureTime']}'),
                            ],
                          ),
                          const SizedBox(width: 130),
                          //待提货
                          GestureDetector(
                            onTap: () => print('提货按钮被点击'),
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 20,
                                vertical: 10,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.red,
                                borderRadius: BorderRadius.circular(30),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black12,
                                    blurRadius: 5,
                                    offset: Offset(0, 3),
                                  ),
                                ],
                              ),
                              child: Text(
                                '提货',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}
